package com.yitongmao.fragment;


import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.RefreshLayout.PullRefreshLayout;
import com.yitongmao.activity.DatailsActivity;
import com.yitongmao.activity.LoginActivity;
import com.yitongmao.activity.SearchActivity;
import com.yitongmao.activity.ShoppingDatailsActivity;
import com.yitongmao.adapter.HomeListViewAdapter;
import com.yitongmao.adapter.HomeListViewAdapter2;
import com.yitongmao.adapter.mHomeGridViewdangjishilingAdapter;
import com.yitongmao.adapter.mHomeGridViewredaishuiguoAdapter;
import com.yitongmao.bean.GoodsListBean;
import com.yitongmao.bean.HomeListBean;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.util.ScreenUtils;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.R;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import com.zhy.autolayout.AutoLinearLayout;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

public class HomeFragment extends Fragment {
    private ListView mHomeListView;
    private PullRefreshLayout layout;
    private ArrayList<int[]> list;
    //状态栏的高度
    private int statusHeight;
    private LinearLayout llSearch;
    private Banner mBanner;
    private View headView;
    private GridView mHomeGridViewdangjishiling;
    private GridView mHomeGridViewredaishuiguo;
    private int a = 1;
    private HomeListViewAdapter homeListViewAdapter;
    private List<HomeListBean.GoodsListBean> goodsList;
    private int b = 1;
    private LoginHuancunBean loginHuancunBean;
    private HomeListBean listBean;
    private List<String> listimage;

    public HomeFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        setNetWork(a, 1);
        // setData();//给banner设置数据

        return view;
    }

    public void initView(View view) {
        SQLiteDatabase db = Connector.getDatabase();
        //头部
        headView = View.inflate(getActivity(), R.layout.homehearitem, null);
        mBanner = (Banner) headView.findViewById(R.id.banner);
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mBanner.setIndicatorGravity(BannerConfig.RIGHT);
        statusHeight = ScreenUtils.getStatusHeight(getActivity());
        llSearch = (LinearLayout) view.findViewById(R.id.ll_search);
        mHomeListView = (ListView) view.findViewById(R.id.mHomeListView);
        layout = (PullRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        //给搜索框设置透明度
        AutoLinearLayout ll_searchedittext = (AutoLinearLayout) view.findViewById(R.id.ll_searchedittext);
        ll_searchedittext.getBackground().setAlpha(150);

        refushLoading();//listview刷新加载
        //添加头部布局
        mHomeListView.addHeaderView(headView);
        //当季时令的GridView
        mHomeGridViewdangjishiling = (GridView) headView.findViewById(R.id.mHomeGridViewdangjishiling);
        mHomeGridViewdangjishiling.setAdapter(new mHomeGridViewdangjishilingAdapter(getActivity()));
        mHomeGridViewdangjishiling.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Gson gson = new Gson();
                String loginId = ACache.get(getActivity()).getAsString("loginId");
                if (loginId != null) {
                    loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
                }
                if (loginHuancunBean == null) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                } else {
                    Intent intent = new Intent(getActivity(), DatailsActivity.class);
                    startActivity(intent);
                }
            }
        });

        //热带水果的GridView
        mHomeGridViewredaishuiguo = (GridView) headView.findViewById(R.id.mHomeGridViewredaishuiguo);
        mHomeGridViewredaishuiguo.setAdapter(new mHomeGridViewredaishuiguoAdapter(getActivity()));
        //监听list滑动状态
        mHomeListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override //监听滑动状态的改变
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override //用于监听ListView屏幕滚动
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //滑动改变导航
                monitor();
            }
        });
        mHomeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Gson gson = new Gson();
                String loginId = ACache.get(getActivity()).getAsString("loginId");
                if (loginId != null) {
                    loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
                }
                if (loginHuancunBean == null) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                } else {
                    Intent intent = new Intent(getActivity(), ShoppingDatailsActivity.class);
                    startActivity(intent);
                }
            }
        });
        //搜索的方法
        search();
        if (!isNetworkConnected(getActivity())) {
            List<GoodsListBean> all = DataSupport.findAll(GoodsListBean.class);
            mHomeListView.setAdapter(new HomeListViewAdapter2(getActivity(), all));
        }
    }

    //刷新加载的方法
    public void refushLoading() {
        //刷新的方法
        layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                llSearch.setVisibility(View.GONE);
                layout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        layout.setRefreshing(false);
                    }
                }, 1000);
            }
        });
        //加载
        layout.setOnLoadListener(new PullRefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                layout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                      /* *//* a++;
                        setNetWork(a,2);*/
                        layout.setLoading(false);
                    }
                }, 1000);
            }
        });
    }

    //给轮播图添加数据
    public void setData() {
        //int[] images = new int[]{R.drawable.banner};
     /*   list = new ArrayList<>();
        list.add(images);*/
        //listviewadapter
        //mHomeListView.setAdapter(new HomeListViewAdapter(getActivity()));

     /*   String[] array = new String[20];
        for (int i = 0; i < array.length; i++) {
            array[i] = "string " + i;
        }*/
       /* mHomeListView.setAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, android.R.id.text1, array));*/
    }

    //banner加载图片
    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            Glide.with(context).load(path).into(imageView);
        }
    }

    public void monitor() {
        int[] ints = new int[2];
        mBanner.getLocationOnScreen(ints);
        /**
         * mImage距离屏幕顶部的距离(图片顶部在屏幕最上面，向上滑动为负数，所以取反)
         * 如果不隐藏状态栏，需要加上状态栏的高度；隐藏状态栏就不用加了；
         */
        int scrollY = -ints[1] + statusHeight;
        //mImage这个view的高度
        int imageHeight = mBanner.getHeight();
        int height = mBanner.getHeight() / 10;
        if (mBanner != null && imageHeight > 0) {
            //如果“图片”没有向上滑动，设置为全透明
            if (scrollY < 0) {
                llSearch.getBackground().setAlpha(0);
            } else {
                //“图片”已经滑动，而且还没有全部滑出屏幕，根据滑出高度的比例设置透明度的比例
                if (scrollY < imageHeight) {
                    int progress = (int) (new Float(scrollY) / new Float(imageHeight) * 255);//255
                    llSearch.getBackground().setAlpha(progress);
                } else {
                    //图片全部滑出屏幕的时候，设为完全不透明
                    llSearch.getBackground().setAlpha(255);
                    llSearch.setBackgroundColor(Color.WHITE);
                }
            }
        }
        if (mBanner != null && height > 0) {
            //如果“图片”没有向上滑动，设置为全透明
            if (scrollY > 0) {
                llSearch.setVisibility(View.VISIBLE);
            } else {
                //“图片”已经滑动，而且还没有全部滑出屏幕，根据滑出高度的比例设置透明度的比例
                if (scrollY < height) {
                    llSearch.setVisibility(View.GONE);
                    int progress = (int) (new Float(scrollY) / new Float(height) * 255);//255
                    llSearch.getBackground().setAlpha(progress);
                } else {
                    //图片全部滑出屏幕的时候，设为完全不透明
                    llSearch.getBackground().setAlpha(255);
                    llSearch.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    public void setNetWork(int page, final int num) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("page", String.valueOf(page));
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.homeUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                //Log.e("onSuccess",result.toString());
                String string = (String) result;
                // Log.e("Gson", "" + string);
                Gson gson = new Gson();
                listBean = gson.fromJson(string, HomeListBean.class);
                goodsList = listBean.goodsList;
                List<HomeListBean.IndexBannerListBean> indexBannerList = listBean.getIndexBannerList();
                listimage = new ArrayList<String>();
                listimage.add(indexBannerList.get(0).jumpUrl);
                listimage.add(indexBannerList.get(0).picUrl);
                listimage.add(indexBannerList.get(1).picUrl);

                mBanner.setImages(listimage);
                //设置图片加载器
                mBanner.setImageLoader(new GlideImageLoader());
                //设置轮播样式
                mBanner.setBannerAnimation(Transformer.ScaleInOut);
                //设置轮播时间
                mBanner.setDelayTime(5500);
                //开始轮播
                mBanner.start();
                if (goodsList == null) {
                    return;
                }
                if (goodsList.equals("") || goodsList.size() < 0) {
                    ToastUtils.showShort(getActivity(), "没有数据");
                } else {
                    b++;
                    if (b == 2) {
                        for (int i = 0; i < goodsList.size(); i++) {
                            GoodsListBean goodsList1 = new GoodsListBean();
                            goodsList1.setDescribes(goodsList.get(i).describes);
                            goodsList1.setGoodsName(goodsList.get(i).goodsName);
                            goodsList1.setId(goodsList.get(i).id);
                            goodsList1.setRetailPrice(goodsList.get(i).retailPrice);
                            goodsList1.setRetailUnit(goodsList.get(i).retailUnit);
                            goodsList1.setState(goodsList.get(i).state);
                            goodsList1.setSubtitle(goodsList.get(i).subtitle);
                            goodsList1.setThumb(goodsList.get(i).thumb);
                            goodsList1.save();
                        }
                    }
                    /*if (goodsList1.save()){
                        ToastUtils.showShort(getActivity(),"成功");
                    }else {
                        ToastUtils.showShort(getActivity(),"失败");
                    }*/
                    if (num == 1) {
                        homeListViewAdapter = new HomeListViewAdapter(getActivity(), goodsList);
                        mHomeListView.setAdapter(homeListViewAdapter);
                    } else if (num == 2) {
                        List<HomeListBean.GoodsListBean> goodsList2 = listBean.goodsList;
                        goodsList.addAll(goodsList2);
                        homeListViewAdapter = new HomeListViewAdapter(getActivity(), goodsList);
                        mHomeListView.setAdapter(homeListViewAdapter);
                        homeListViewAdapter.notifyDataSetChanged();
                    }
                }
                mHomeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Gson gson = new Gson();
                        String loginId = ACache.get(getActivity()).getAsString("loginId");
                        if (loginId != null) {
                            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
                        }
                        if (loginHuancunBean == null) {
                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                            startActivity(intent);
                            getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                        } else {
                            Intent intent = new Intent(getActivity(), ShoppingDatailsActivity.class);
                            int shoppingId = goodsList.get(position - 1).id;
                            int userId = loginHuancunBean.userInfo.id;
                            intent.putExtra("shoppingId", String.valueOf(shoppingId));
                            intent.putExtra("userId", String.valueOf(userId));
                            startActivity(intent);
                        }
                    }
                });
            }

            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }

    //点击搜索跳转到搜索页面
    public void search() {
        llSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });
    }

    //判断网络
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

}